import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import sessionService from '@/services/sessionService'
import type { Session } from '@/types/session'

export const useSessionStore = defineStore('session', () => {
  const sessions = ref<Session[]>([])
  const isLoadingSessions = ref(false)
  const searchKeyword = ref('')
  const pagination = ref({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })
  const currentId = ref<string>(localStorage.getItem('currentSessionId') || '')
  const selectedSession = ref<Session | null>(null)

  const currentSession = computed<Session | null>(() => {
    return sessions.value.find((session) => session.id === currentId.value) ?? null
  })

  const setCurrentSession = (sessionId: string | null) => {
    if (!sessionId) {
      currentId.value = ''
      selectedSession.value = null
      localStorage.removeItem('currentSessionId')
      return
    }
    currentId.value = sessionId
    localStorage.setItem('currentSessionId', sessionId)
    const found = sessions.value.find((session) => session.id === sessionId) ?? null
    selectedSession.value = found
  }

  const upsertSession = (session: Session) => {
    const index = sessions.value.findIndex((item) => item.id === session.id)
    if (index === -1) {
      sessions.value.unshift(session)
    } else {
      sessions.value.splice(index, 1, session)
    }
  }

  const loadSessions = async () => {
    isLoadingSessions.value = true
    try {
      const { currentPage, pageSize } = pagination.value
      const offset = (currentPage - 1) * pageSize

      const response = await sessionService.getSessions({
        limit: pageSize,
        offset,
        search: searchKeyword.value || undefined
      })

      const fetchedSessions = Array.isArray(response.sessions) ? response.sessions : []
      sessions.value = fetchedSessions
      pagination.value.total = response.total ?? 0

      if (!currentId.value && sessions.value.length > 0) {
        setCurrentSession(sessions.value[0].id)
      } else if (currentId.value && !sessions.value.some((session) => session.id === currentId.value)) {
        setCurrentSession(sessions.value[0]?.id ?? null)
      } else if (currentId.value) {
        setCurrentSession(currentId.value)
      }
    } catch (error) {
      console.error('加载会话列表失败:', error)
      sessions.value = []
      pagination.value.total = 0
      setCurrentSession(null)
      throw error
    } finally {
      isLoadingSessions.value = false
    }
  }

  const ensureSessionExists = async (sessionId: string, title?: string) => {
    if (!sessionId) {
      return
    }
    if (sessions.value.some((session) => session.id === sessionId)) {
      return
    }
    try {
      await sessionService.createSession({ id: sessionId, title })
      await loadSessions()
    } catch (error: any) {
      const status = error?.response?.status
      if (status === 409) {
        await loadSessions()
        return
      }
      console.warn('确保会话存在失败:', error)
    }
  }

  const createSession = async (data: { id?: string; title?: string } = {}) => {
    const session = await sessionService.createSession(data)
    upsertSession(session)
    setCurrentSession(session.id)
    pagination.value.total += 1
    return session
  }

  const deleteSession = async (sessionId: string) => {
    await sessionService.deleteSession(sessionId)
    const nextSessions = sessions.value.filter((session) => session.id !== sessionId)
    sessions.value = nextSessions
    pagination.value.total = Math.max(0, pagination.value.total - 1)
    if (currentId.value === sessionId) {
      setCurrentSession(nextSessions[0]?.id ?? null)
    }
  }

  const renameSession = async (sessionId: string, newName: string) => {
    if (!newName?.trim()) {
      return
    }
    const updated = await sessionService.updateSession(sessionId, { title: newName })
    upsertSession(updated)
    if (currentId.value === sessionId) {
      setCurrentSession(sessionId)
    }
  }

  const searchSessions = async (keyword: string) => {
    searchKeyword.value = keyword
    pagination.value.currentPage = 1
    await loadSessions()
  }

  const clearSearch = async () => {
    searchKeyword.value = ''
    pagination.value.currentPage = 1
    await loadSessions()
  }

  return {
    sessions,
    isLoadingSessions,
    searchKeyword,
    pagination,
    currentId,
    currentSession,
    selectedSession,
    setCurrentSession,
    loadSessions,
    ensureSessionExists,
    createSession,
    deleteSession,
    renameSession,
    searchSessions,
    clearSearch
  }
})
